package www.openteam.com.ui.business;


import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.getbase.floatingactionbutton.FloatingActionButton;
import com.getbase.floatingactionbutton.FloatingActionsMenu;
import com.google.gson.Gson;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import www.openteam.com.R;
import www.openteam.com.adapter.bussiness.LoadingLstAdp;
import www.openteam.com.base.mBaseFragment;
import www.openteam.com.bean.AddDeliverNote;
import www.openteam.com.bean.CoShipBusAllLst;
import www.openteam.com.bean.LdLst_dlrtNote;
import www.openteam.com.bean.ShipBus;
import www.openteam.com.bean.ShipBusList;
import www.openteam.com.bean.UpdateInfo;
import www.openteam.com.contract.business.LoadListContract;
import www.openteam.com.presenter.business.LoadListPresenter;
import www.openteam.com.tool.ToastUtil;
import www.openteam.com.view.DialogUtil;
import www.openteam.com.view.MItemRemoveRecycleView;


/**
 * A simple {@link Fragment} subclass.
 * 装车清单
 */
public class LoadingListFragment extends mBaseFragment<LoadListPresenter>
        implements LoadListContract.LoadListView {


    @Bind(R.id.load_list_serchview)
    SearchView loadListSerchview;
    @Bind(R.id.load_list_scan)
    AppCompatImageView loadListScan;
    @Bind(R.id.load_list_number)
    TextView loadListNumber;
    @Bind(R.id.load_list_man)
    TextView loadListMan;
    @Bind(R.id.load_list_date)
    TextView loadListDate;
    @Bind(R.id.load_list_address)
    TextView loadListAddress;
    @Bind(R.id.load_list_factory)
    TextView loadListFactory;
    @Bind(R.id.load_list_carNumb)
    TextView loadListCarNumb;
    @Bind(R.id.load_list_counterNumb)
    TextView loadListCounterNumb;
    @Bind(R.id.load_list_status)
    TextView loadListStatus;
    @Bind(R.id.load_list_remake)
    TextView loadListRemake;
    @Bind(R.id.load_list_recycleView)
    MItemRemoveRecycleView mItemRemoveRecycleView;
    @Bind(R.id.load_list_add)
    Button loadListAdd;
    @Bind(R.id.examine)
    FloatingActionButton examine;
    @Bind(R.id.unexamine)
    FloatingActionButton unexamine;
    @Bind(R.id.delete)
    FloatingActionButton delete;
    @Bind(R.id.keep)
    FloatingActionButton keep;
    @Bind(R.id.multiple_actions)
    FloatingActionsMenu multipleActions;
    @Bind(R.id.load_list_add_serchview)
    SearchView loadListAddSerchview;
    private int RESULT_LOAD = 1;
    private int RESULT_ADD = 2;
    private String TAG = getClass().getSimpleName();
    private Intent intent;
    private String rdsno;
    //装车清单的id，存到送货单的zbid
    private String zbid;
    private String checker;
    private int maxId;
    private int status = 0;
    private int issave = 1;
    private LoadingLstAdp loadingLstAdp;
    private List<LdLst_dlrtNote> old_ldLstDlrtList = new ArrayList<>();
    private List<LdLst_dlrtNote> new_ldLstDlrtList = new ArrayList<>();
    private List<CoShipBusAllLst> isDelete_lst = new ArrayList<>();
    private DialogUtil dialogUtil;

    public LoadingListFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_loading_list, container, false);
        ButterKnife.bind(this, view);
        mPresenter = loadPresenter();
        initData();
        initView();
        initListener();
        return view;
    }

    @Override
    protected void initData() {
        if (mPresenter != null)
            mPresenter.attachView(this);
        intent = new Intent(getActivity(), ScanActivity.class);
        maxId = 0;
        new_ldLstDlrtList.clear();
        old_ldLstDlrtList.clear();
        isDelete_lst.clear();
        mProgressDialog = new ProgressDialog(getContext());
        dialogUtil = new DialogUtil();
    }

    @Override
    protected void initListener() {
        //打开装车清单扫描
        loadListScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(intent, RESULT_LOAD);
            }
        });
        //查询框输入装车清单单号
        loadListSerchview.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                rdsno = query;
                mPresenter.getShipBus(rdsno);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });

        //送货单通过查询框添加
        loadListAddSerchview.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                if (status == 1) {
                    ToastUtil.showToast(getContext(), "该清单已经审核，不可操作");
                    return false;
                }
//        startActivityForResult(intent, RESULT_ADD);
                mPresenter.addDeliverNote(query);
                mProgressDialog.show();
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });

        //审核
        examine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (issave == 0) {
                    ToastUtil.showToast(getContext(), "请先保存");
                    return;
                }
                dialogUtil.show(getContext(), "是否进行审核", new DialogUtil.DialogButtonListener() {
                    @Override
                    public void sure() {
                        mPresenter.audit(zbid, checker, getCurrentTime());
                        mProgressDialog.show();
                    }

                    @Override
                    public void cancel() {
                    }
                });
            }
        });

        unexamine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialogUtil.show(getContext(), "是否进行反审核", new DialogUtil.DialogButtonListener() {
                    @Override
                    public void sure() {
                        mPresenter.unaudit(zbid);
                        mProgressDialog.show();
                    }

                    @Override
                    public void cancel() {
                    }
                });
            }
        });

        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (status == 1) {
                    ToastUtil.showToast(getContext(), "该清单已经审核，不可删除");
                    return;
                }
                mPresenter.deleteLoadingListNote(zbid);
                mProgressDialog.show();
            }
        });
        keep.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (status == 1) {
                    ToastUtil.showToast(getContext(), "该清单已经审核，不可操作");
                    return;
                }
                Gson gson = new Gson();
                try {
                    String new_str = gson.toJson(new_ldLstDlrtList);
                    String old_str = gson.toJson(isDelete_lst);
                    new_str = URLEncoder.encode(new_str, "UTF-8");
                    old_str = URLEncoder.encode(old_str, "UTF-8");
                    mPresenter.insertDlertNote(new_str, old_str);
                    mProgressDialog.show();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    @Override
    protected void initView() {
        loadListSerchview.setSubmitButtonEnabled(true);
        loadListSerchview.onActionViewExpanded();
        loadListAddSerchview.setSubmitButtonEnabled(true);
        loadListAddSerchview.onActionViewExpanded();

        linearLayoutManager = new LinearLayoutManager(getActivity());
        mItemRemoveRecycleView.setLayoutManager(linearLayoutManager);
        loadingLstAdp = new LoadingLstAdp(getContext());
    }

    @Override
    protected void otherViewClick(View view) {

    }

    @Override
    protected LoadListPresenter loadPresenter() {
        return new LoadListPresenter();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick(R.id.load_list_add)//送货单添加
    public void onViewClicked() {
        if (status == 1) {
            ToastUtil.showToast(getContext(), "该清单已经审核，不可操作");
            return;
        }
        startActivityForResult(intent, RESULT_ADD);
//        mPresenter.addDeliverNote(loadListAddSerchview.getQuery().toString());
//        mProgressDialog.show();
    }


    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        String work_order_id = data.getStringExtra("work_order_id");
        if (requestCode == RESULT_LOAD && !work_order_id.equals("")) {
            loadListSerchview.setQuery(work_order_id, true);
        } else if (requestCode == RESULT_ADD && !work_order_id.equals("")) {
//            mPresenter.addDeliverNote(work_order_id);
            loadListAddSerchview.setQuery(work_order_id,true);
            mProgressDialog.show();
        }
    }

    @Override
    public void onRefresh() {

    }


    @Override
    public void getShioBusSucces(ShipBus shipBus) {
        if (1005 == shipBus.getStatus()) {
            ToastUtil.showToast(getContext(), shipBus.getInfo());
        } else {
            maxId = 0;
            new_ldLstDlrtList.clear();
            old_ldLstDlrtList.clear();
            isDelete_lst.clear();
            ShipBus.DataBeanX.DataBean dataBean = shipBus.getData().getData().get(0);
            mPresenter.getShipBusList(dataBean.getId());
            mProgressDialog.show();
            loadListNumber.setText(dataBean.getRdsno());
            loadListMan.setText(dataBean.getSender());
            loadListDate.setText(dataBean.getSenddate());
            loadListAddress.setText(dataBean.getSendaddress());
            loadListFactory.setText(dataBean.getShipComp());
            loadListCarNumb.setText(dataBean.getForeignplates());
            loadListCounterNumb.setText(dataBean.getConCarNo());
            status = dataBean.getStatus();
            loadListStatus.setText((status == 1) ? "已审核" : "未审核");
            if (status == 1) {
                examine.setVisibility(View.GONE);
                unexamine.setVisibility(View.VISIBLE);
            } else if (status == 0) {
                examine.setVisibility(View.VISIBLE);
                unexamine.setVisibility(View.GONE);
            }
            zbid = dataBean.getId();
            checker = dataBean.getInputer();
        }
    }

    @Override
    public void getShipBusFail(String msg) {
        mProgressDialog.cancel();
        ToastUtil.showToast(getContext(), msg);

    }

    @Override
    public void getShioBusListSucces(ShipBusList shipBusList) {
        mProgressDialog.cancel();
        if (1005 == shipBusList.getStatus()) {
            ToastUtil.showToast(getContext(), shipBusList.getInfo());
        } else {
            final List<ShipBusList.DataBeanX.DataBean> dataBeanList = shipBusList.getData().getData();
//        ShipBusList.DataBeanX.DataBean dataBean = shipBusList.getData().getData().get(0);
            for (ShipBusList.DataBeanX.DataBean dataBean : dataBeanList) {
                LdLst_dlrtNote ldLst_dlrtNote = new LdLst_dlrtNote();
                ldLst_dlrtNote.setId(dataBean.getId() + "");
                ldLst_dlrtNote.setZbid(dataBean.getZbid() + "");
                ldLst_dlrtNote.setSendNo(dataBean.getSendNo());
                ldLst_dlrtNote.setCustid(dataBean.getCustid());
                ldLst_dlrtNote.setSendAddress(dataBean.getSendAddress());
                ldLst_dlrtNote.setBoxNumb(dataBean.getBoxNumb() + "");
                ldLst_dlrtNote.setBoxPackages(dataBean.getBoxPackages() + "");
                old_ldLstDlrtList.add(ldLst_dlrtNote);
                maxId = (maxId < dataBean.getId()) ? dataBean.getId() : maxId;
            }
            loadingLstAdp.setmSortedList(old_ldLstDlrtList);
            mItemRemoveRecycleView.setAdapter(loadingLstAdp);
            mItemRemoveRecycleView.setOnItemClickListener(new MItemRemoveRecycleView.ItemOnListener() {
                @Override
                public void onItemDelete(int position) {
                    if (status == 1) {
                        ToastUtil.showToast(getContext(), "该清单已经审核，不可操作");
                        return;
                    }
                    issave = 0;
                    isDelete_lst.add(loadingLstAdp.getcoShipAllBus(position));
                    mItemRemoveRecycleView.removeViewAt(position);
                    loadingLstAdp.removeItem(position);
                }
            });
        }

    }


    @Override
    public void getShipBusListFail(String msg) {
        mProgressDialog.cancel();
        ToastUtil.showToast(getContext(), msg);
    }

    @Override
    public void addDeliverNoteSucces(AddDeliverNote addDeliverNote) {
        Log.e(TAG, "addDeliverNoteSucces: ");
        mProgressDialog.cancel();
        if (1005 == addDeliverNote.getStatus()) {
            ToastUtil.showToast(getContext(), addDeliverNote.getInfo());
        } else {
            AddDeliverNote.DataBeanX.DataBean dataBean = addDeliverNote.getData().getData().get(0);
            LdLst_dlrtNote ldLst_dlrtNote = new LdLst_dlrtNote();
            maxId++;
            ldLst_dlrtNote.setId(maxId + "");
            ldLst_dlrtNote.setZbid(zbid);
            ldLst_dlrtNote.setCustid(dataBean.getCustID());
            ldLst_dlrtNote.setSendNo(dataBean.getRdsNo());
            ldLst_dlrtNote.setSendAddress(dataBean.getSendaddress());
            ldLst_dlrtNote.setBoxNumb(dataBean.getBoxNumb() + "");
            ldLst_dlrtNote.setBoxPackages(dataBean.getBoxPackages() + "");
            new_ldLstDlrtList.add(ldLst_dlrtNote);
            loadingLstAdp.addItem(ldLst_dlrtNote);
            issave = 0;
        }

    }

    @Override
    public void addDeliverNoteFail(String msg) {
        mProgressDialog.cancel();
        ToastUtil.showToast(getContext(), msg);
    }

    @Override
    public void updateDlertNoteSuccess(UpdateInfo info) {
        Log.e(TAG, "updateDlertNoteSuccess: ");
        mProgressDialog.cancel();
        ToastUtil.showToast(getContext(), info.getInfo());
        maxId = 0;
        issave = 1;
//        new_ldLstDlrtList.clear();
//        old_ldLstDlrtList.clear();
//        isDelete_lst.clear();
        mPresenter.getShipBus(rdsno);

    }

    @Override
    public void updateDlertNoteFail(String msg) {
        mProgressDialog.cancel();
        Log.e(TAG, "updateDlertNoteFail: ");
        ToastUtil.showToast(getContext(), msg);
        mPresenter.getShipBus(rdsno);
    }

    @Override
    public void deleteDeliverNoteSuccess(UpdateInfo msg) {

    }

    @Override
    public void deleteDeliverNoteFail(String info) {

    }

    @Override
    public void deleteLoadingListNoteSuccess(UpdateInfo msg) {
        mProgressDialog.cancel();
        ToastUtil.showToast(getContext(), msg.getInfo());
        maxId = 0;
        new_ldLstDlrtList.clear();
        old_ldLstDlrtList.clear();
        isDelete_lst.clear();
        loadingLstAdp.clear();
        status = 0;
        clearTextView(loadListNumber);
        clearTextView(loadListMan);
        clearTextView(loadListDate);
        clearTextView(loadListAddress);
        clearTextView(loadListFactory);
        clearTextView(loadListCarNumb);
        clearTextView(loadListCounterNumb);
        clearTextView(loadListStatus);
        zbid = "";
        checker = "";
        rdsno = "";
        issave = 1;
        loadListSerchview.setQuery("", false);


    }

    private void clearTextView(TextView tv) {
        tv.setText("");
    }

    @Override
    public void deleteLoadingListNoteFail(String info) {
        mProgressDialog.cancel();
        ToastUtil.showToast(getContext(), info);
    }

    @Override
    public void auditSuccess(UpdateInfo info) {
        mProgressDialog.cancel();
        ToastUtil.showToast(getContext(), info.getInfo());
        status = 0;
//        examine.setTitle("反审核");
//        loadListStatus.setText("未审核");
//        Log.e(TAG, "auditSuccess: 反审核" );
        mPresenter.getShipBus(rdsno);
    }

    @Override
    public void auditFail(String msg) {
        mProgressDialog.cancel();
        ToastUtil.showToast(getContext(), msg);
    }

    @Override
    public void unauditSuccess(UpdateInfo info) {
        mProgressDialog.cancel();
        ToastUtil.showToast(getContext(), info.getInfo());
        status = 1;
//        examine.setTitle("审核");
//        loadListStatus.setText("已审核");
//        Log.e(TAG, "unauditSuccess: 审核" );
        mPresenter.getShipBus(rdsno);
    }

    @Override
    public void unauditFail(String msg) {
        mProgressDialog.cancel();
        ToastUtil.showToast(getContext(), msg);
    }

    String getCurrentTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(new Date());
        return date;
    }
}
